//
//  FQDRevealRefreshHeader.m
//  FakeQDaily
//
//  Created by mewxiv on 8/21/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDRevealRefreshHeader.h"

// 太阳想对地面上升的最大高度
static CGFloat const FQDSunRiseMaxHeight = 80.0f;
// 太阳旋转动画的keyPath
static NSString * const FQDAnimationKeyPathSunRotation = @"FQDAnimationKeyPathSunRotation";

@interface FQDRevealRefreshHeader ()
@property (nonatomic, assign) BOOL isSunRotating;
// 地面
@property (nonatomic, strong) UIImageView *groundImageView;
// 太阳
@property (nonatomic, strong) UIImageView *sunImageView;
// sunImageView的容器，负责执行太阳上升的动画
@property (nonatomic, strong) UIView *sunImageContainerView;
// 遮罩层，当没有下拉时所有可视元素都被遮罩层遮挡
@property (nonatomic, strong) UIView *maskView;
// 判断是否即将停止刷新状态
@property (nonatomic, assign) BOOL isEndingRefreshing;
@end

@implementation FQDRevealRefreshHeader

- (void)prepareUI
{
    [super prepareUI];
    
    self.isEndingRefreshing = NO;
    
    UIImage *groundImage = [UIImage imageNamed:@"reveal_refresh_foreground"];
    UIImageView *groundImageView = [[UIImageView alloc] initWithImage:groundImage];
    groundImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:groundImageView];
    self.groundImageView = groundImageView;
    
    UIView *sunBackgroundView = [[UIView alloc] init];
    [self addSubview:sunBackgroundView];
    self.sunImageContainerView = sunBackgroundView;
    
    UIImage *sunImage = [UIImage imageNamed:@"reveal_refresh_sun"];
    UIImageView *sunImageView = [[UIImageView alloc] initWithImage:sunImage];
    [sunBackgroundView addSubview:sunImageView];
    self.sunImageView = sunImageView;
    
    self.maskView = [[UIView alloc] init];
    [self addSubview:self.maskView];
    [self bringSubviewToFront:self.maskView];
    
    self.backgroundColor = [UIColor whiteColor];
}

- (void)prepareLayoutWithFrame:(CGRect)frame
{
    [super prepareLayoutWithFrame:frame];
    
    // 偏移12像素，让建筑下面的地平线贴边
    CGFloat x = 0;
    CGFloat y = 12.0f;
    CGFloat w = frame.size.width;
    CGFloat h = self.refreshHeight;
    self.groundImageView.frame = CGRectMake(x, y, w, h);
    
    CGFloat sunDimension = 30.0f;
    CGFloat sunX = w / 2 - 120.0f;
    CGFloat sunY = CGRectGetMaxY(self.groundImageView.frame) - sunDimension;
    self.sunImageContainerView.frame = CGRectMake(sunX, sunY, sunDimension, sunDimension);
    
    self.maskView.frame = CGRectMake(0, 0, w, h + sunDimension);
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    if ([newSuperview isKindOfClass:[UIScrollView class]]) {
        self.maskView.backgroundColor = newSuperview.backgroundColor;
    }
}

- (void)animateDraggingWithProgress:(CGFloat)progress
{
    // 拖动距离小于自身高度时，相对屏幕静止，超过时跟随拖动下移
    CGFloat refreshViewHeight = self.refreshHeight;
    CGFloat normalizedProgress = MIN(MAX(progress, 0), 1);
    CGFloat groundOffsetY = -(refreshViewHeight * normalizedProgress);
    self.frame = CGRectOffset(self.bounds, 0, groundOffsetY);
    
    CGFloat maskViewOffsetY = (refreshViewHeight * progress);
    self.maskView.frame = CGRectOffset(self.maskView.bounds, 0, maskViewOffsetY);
    
    // 非刷新状态下，分三个阶段根据进度播放太阳上升动画
    CGFloat sunOffsetY = 0;
    CGFloat anchorProgress = FQDSunRiseMaxHeight / refreshViewHeight;
    if (progress <= anchorProgress) {
        // 地面相对屏幕静止，太阳相对地面高度未达到最大，以与拖动同样的速度上升太阳
        sunOffsetY = -refreshViewHeight * progress;
    }
    else if (progress < 1.0) {
        // 地面相对屏幕静止，太阳相对地面高度达到最大，高度不再改变
        sunOffsetY = -FQDSunRiseMaxHeight;
    }
    else {
        // 地面跟随拖动下移，太阳以与拖动同样的速度上升，但结果是太阳相对屏幕静止
        CGFloat offsetY = refreshViewHeight*(self.progress - 1);
        sunOffsetY = -FQDSunRiseMaxHeight - offsetY;
    }
    
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0, sunOffsetY);
    self.sunImageContainerView.transform = transform;
    
    // 太阳相对地面高度未达到最大前根据拖拽进度交互式播放旋转动画，达到后开始自动旋转
    if (progress <= 0 && !self.isEndingRefreshing) {
        self.isRefreshing ? [self stopSunRotation] : nil;
    }
    else if (progress < anchorProgress) {
        CGFloat angle = M_PI * progress;
        self.sunImageView.transform = CGAffineTransformMakeRotation(angle);
    }
    else {
        self.isSunRotating ? : [self startSunRotation];
    }
}

- (void)willBeginRefreshing
{
    CGFloat sunOffsetY = -FQDSunRiseMaxHeight;
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0, sunOffsetY);
    
    [UIView animateWithDuration:FQDRefreshPullDownAnimationDuration animations:^{
        self.sunImageContainerView.transform = transform;
    }];
    
}

- (void)willEndRefreshing
{
    self.isEndingRefreshing = YES;
}

- (void)didEndRefreshing
{
    // 停止刷新时（RefreshHeader已经全部被遮挡），停止旋转动画
    [self stopSunRotation];
    self.isEndingRefreshing = NO;
}

- (void)startSunRotation
{
    if (self.isSunRotating) {
        return;
    }
    
    self.isSunRotating = YES;
    
    CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotation.fromValue = @0;
    rotation.toValue = @(M_PI);
    rotation.repeatCount = INFINITY;
    rotation.duration = 0.6f;
    [self.sunImageView.layer addAnimation:rotation forKey:FQDAnimationKeyPathSunRotation];
}

- (void)stopSunRotation
{
    self.isSunRotating = NO;
    [self.sunImageView.layer removeAnimationForKey:FQDAnimationKeyPathSunRotation];
}

@end
